package com.idanchuang.component.redis;

import com.idanchuang.component.redis.annotation.RedisLock;
import com.idanchuang.component.redis.util.DRedisLocks;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author yjy
 * @date 2020/5/8 10:21
 **/
@Component
public class LockService {

    private static int a = 0;

    @Transactional
    @RedisLock(value = "customLockName:88888222", lockTimeout = 60000L, tryTimeout = 20000L)
    public void doSomething() {
        a ++;
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("a: " + a);
    }

    public void recursion() {
        System.out.println("recursion: " + reduce(10, 1));
    }

    private int reduce(int x, int y) {
        return DRedisLocks.runWithLock("hhhhxxxxx", () -> {
            int a = x - y;
            System.out.println("reduce res: " + a);
            if (a <= 0) {
                return a;
            } else {
                return reduce(a, y);
            }
        });
    }

}
